package com.chenwenxuan.sync.console.dao;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;

import com.chenwenxuan.sync.console.model.TaskArg;
import com.chenwenxuan.sync.console.model.TaskArgs;

public class TaskArgDao extends AbstractDao {
	
	private final static String getTaskArgsSql = "select TASK_ID, ARG_ID, ARG_NAME, ARG_VALUE, ARG_ORDER, ARG_TYPE from TASK_ARGS t where t.task_id = ?";
	private final static String deleteTaskArgsSql = "delete from TASK_ARGS t where t.task_id = ?";
	private final static String updateTaskArgsSql = "insert into TASK_ARGS(TASK_ID, ARG_ID, ARG_NAME, ARG_VALUE, ARG_ORDER, ARG_TYPE) values (?,?,?,?,?,?)";
	
	@SuppressWarnings("unchecked")
	public TaskArgs getTaskArgs(int taskId){
		
		List <TaskArg> list = getJdbcTemplate().query(getTaskArgsSql, new Object[]{taskId}, new RowMappers.TaskArgRowMapper());
		TaskArgs args = new TaskArgs();
		args.setTaskArg(list);
		args.setTaskId(taskId);
		return args;
		
	}
	
	public void deleteTaskArgs(int taskId) {
		getJdbcTemplate().update(deleteTaskArgsSql, new Object[]{taskId});
	}
	
	public void addTaskArgs(TaskArgs args) {
		updateTaskArgs(args);
	}
	
	public void updateTaskArgs(final TaskArgs args) {
		
		deleteTaskArgs(args.getTaskId());
		final TaskArg[] argArray = args.getTaskArgAsArray();
		
		getJdbcTemplate().batchUpdate(updateTaskArgsSql, new BatchPreparedStatementSetter() {
			
			@Override
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				int k = 0;
				ps.setInt(k++, argArray[i].getTaskId());
				ps.setInt(k++, argArray[i].getArgId());
				ps.setString(k++, argArray[i].getArgName());
				ps.setString(k++, argArray[i].getArgValue());
				ps.setInt(k++, argArray[i].getArgOrder());
				ps.setString(k++, argArray[i].getArgType());
			}
			
			@Override
			public int getBatchSize() {
				return argArray.length;
			}
		});
	}

}
